package com.example.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.MD5;
import com.example.common.jwt.JwtTokenUtils;
import com.example.common.utils.R;
import com.example.dao.UserMapper;
import com.example.entity.User;
import com.example.entity.Params;
import com.example.entity.UserDTO;
import com.example.service.UserService;
import com.github.pagehelper.PageInfo;
import com.wf.captcha.utils.CaptchaUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.example.controller.CaptureController.CAPTURE_MAP;

@CrossOrigin
@RestController
@Api(tags = "用户管理")
@RequestMapping("/user")
public class UserController {


    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;


    @PostMapping("/login")
    @ApiOperation(value = "登陆", notes = "使用用户名和密码进行登陆，并验证验证码")
    public R login(@RequestBody User user, @RequestParam String key, HttpServletRequest request) {
        String value = CAPTURE_MAP.get(key);
        if (ObjectUtil.isEmpty(user.getVerCode())) {
            return R.error("请输入验证码");
        }
        if (!user.getVerCode().toLowerCase().equals(value)) {
            // 清除session中的验证码
            CaptchaUtil.clear(request);
            return R.error("验证码不正确");
        }
        User loginUser = userService.login(user);
        return R.success(loginUser);
    }

    @PostMapping("/password")
    @ApiOperation(value = "修改密码", notes = "根据当前用户的token修改密码，验证原密码是否正确")
    public R updatePassword(@RequestBody User user) {
        User currentUser = JwtTokenUtils.getCurrentUser();
        Integer currentUserId = currentUser.getId();
        if (ObjectUtil.isNull(currentUser)) {
            return R.error("token验证失效，请重新登陆");
        }
        if (!user.getPassword().equals(currentUser.getPassword())) {
            return R.error("原密码输入错误");
        }

        user.setPassword(MD5.create().digestHex(user.getNewPassword().getBytes()));

        userService.update(user);
        return R.success();
    }

    @PostMapping("/register")
    @ApiOperation(value = "注册", notes = "注册新用户")
    public R register(@RequestBody User user) {
        userService.add(user);
        return R.success();
    }

    @PostMapping
    @ApiOperation(value = "保存用户", notes = "根据用户ID判断是新增还是更新用户")
    public R save(@RequestBody User user) {
        if (user.getId() == null) {
            userService.add(user);
        } else {
            userService.update(user);
        }
        return R.success();
    }

    @GetMapping
    @ApiOperation(value = "获取所有用户", notes = "获取所有用户的列表")
    public R findAll() {
        List<User> list = userService.findAll();
        return R.success(list);
    }

    @GetMapping("/search")
    @ApiOperation(value = "根据条件搜索用户", notes = "根据传入的参数进行用户搜索，支持分页")
    public R findBySearch(Params params) {
        PageInfo<User> info = userService.findBySearch(params);
        return R.success(info);
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除用户", notes = "根据用户ID删除用户")
    public R delete(@PathVariable Integer id) {
        userService.delete(id);
        return R.success();
    }

    @PostMapping("/upload")
    @ApiOperation(value = "上传头像", notes = "上传头像到Minio")
    public R upload(MultipartFile file, @RequestParam String username) {
        try {
            // 调用 UserService 进行上传处理
            userService.upload(file,username);
            // 返回成功响应
            return R.success();
        } catch (Exception e) {
            // 返回失败响应
            return R.error("上传失败");
        }
    }

    @GetMapping("/getCurrentUser")
    @ApiOperation(value = "获取当前用户信息", notes = "通过 Token 获取当前登录用户的最新信息")
    public R getCurrentUser(HttpServletRequest request) {
        User currentUser = JwtTokenUtils.getCurrentUser();
        Integer currentUserId = currentUser.getId();
        if (ObjectUtil.isNull(currentUser)) {
            return R.error("未登录或 token 已失效");
        }

        // 通过 ID 从数据库查询最新用户信息
        User updatedUser = userService.findById(currentUser.getId());
        if (ObjectUtil.isNull(updatedUser)) {
            return R.error("用户不存在或已被删除");
        }

        return R.success(updatedUser);
    }



}
